package lol.clann.minecraft.springboot.plugin.bukkit.command.resolver;

import lol.clann.minecraft.springboot.api.bukkit.command.resolver.CommandResolver;
import lol.clann.minecraft.springboot.api.bukkit.command.resolver.CommandResolverFactory;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.ResolvableType;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author pyz
 * @date 2019/5/6 10:10 PM
 */
@Slf4j
@Component
public class CommandResolvers implements BeanPostProcessor {
    private static final List<CommandResolverFactory> factories = new ArrayList<>();
    private static final Map<Type, CommandResolver> parsers = new HashMap<>();
    @Getter
    private static final CommandResolver booleanFlagResolver = (sender, arg, type) -> arg != null;

    public static CommandResolver getResolver(Type type) {
        CommandResolver resolver = parsers.get(type);
        if (resolver != null) {
            return resolver;
        }
        Class clazz = ResolvableType.forType(type).resolve();
        for (CommandResolverFactory factory : factories) {
            if (factory.canResolve(clazz)) {
                resolver = factory.getResolver(clazz);
                parsers.put(type, resolver);
                return resolver;
            }
        }
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof CommandResolverFactory) {
            factories.add((CommandResolverFactory) bean);
        }
        return bean;
    }
}
